package com.caac.core.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.caac.core.Global;
import com.caac.core.service.UserManager;
import com.caac.core.web.util.AuthenticationUtils;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright Intolong 2004</p>
 * <p>Company: Intolong</p>
 * @author <a href="mailto:intolong@163.com">Intolong</a>
 * @version 1.0
 */

public class AuthenticationFilter extends BaseFilter {
    private static final String KEY_LOGIN = Global.KEY_LOGIN;
    private static final String KEY_USER_MANAGER = Global.KEY_USER_MANAGER;

    private String loginPage;

    public void init(FilterConfig config) throws ServletException {
        super.init(config);
        loginPage = config.getInitParameter(KEY_LOGIN);
    }

    public void doFilter(ServletRequest req,
                         ServletResponse res,
                         FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if (isAuthenticated(request, response)) {
            chain.doFilter(req, res);
        } else {
            response.sendRedirect(request.getContextPath() + loginPage);
            return;
        }
    }

    public void destroy() {
        loginPage = null;
        super.destroy();
    }

    private UserManager getUserManager() {
        return (UserManager) getBean(KEY_USER_MANAGER);
    }

    private boolean isAuthenticated(HttpServletRequest request,
                                    HttpServletResponse response) {
        return AuthenticationUtils.isAuthenticated(request, response,
                getUserManager());
    }
}
